package com.example.myys.ui.page.mhPage

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.FabPosition
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myys.common.TopItem
import com.example.myys.data.entity.DataBean
import com.example.myys.ui.Resource
import com.example.myys.ui.StateHandler
import com.example.myys.ui.base.DialogWithImage
import com.example.myys.ui.base.ListItem
import com.example.myys.ui.base.PickSth
import com.example.myys.ui.base.SearchBar
import com.example.myys.viewModel.mhModel.MhSjViewModel

//顶部导航栏数据定义
object PagesMh {
    const val SC = "Sc" //收藏
    const val Tj = "Tj" //推荐
    const val MHNR = "Mhnr" //漫画内容
}
//漫画展示
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Mh(navController: NavController, modifier: Modifier) {
    val mhViewModel: MhSjViewModel = viewModel()
    val scTjState by mhViewModel.scTjState.collectAsState()
    val sjState by mhViewModel.sjState.collectAsState()
    //导航
    val dataBar= listOf(
        TopItem(PagesMh.SC,"收藏"),
        TopItem(PagesMh.Tj,"推荐")
    )
    var state by remember { mutableStateOf(0) }
    val scope= rememberCoroutineScope()
    Column {
        ScrollableTabRow(selectedTabIndex = state) {
            dataBar.forEachIndexed { index, item ->
                Tab(text = {
                    Text(text = item.label)
                }, selected = state == index, onClick = {
                    state = index
                })
            }
        }
        when (state) {
                0-> MhSj(sjState,navController,mhViewModel)
                1-> MhSc(scTjState,navController,mhViewModel)
            }

    }
}

//漫画书架
@Composable
fun MhSj(sjState: Resource<List<DataBean>>, navController: NavController, marsViewModel: MhSjViewModel) {
    Scaffold(floatingActionButton = {
        FloatingActionButton(onClick = { /*TODO*/ }) {
            PickSth{filePath,fileName->
                Log.d("[TestPick]", "picked a file ${fileName}. path:${filePath.toString()}")
            }
        }
    },
        floatingActionButtonPosition = FabPosition.End
    ) { padding->
        StateHandler(state = sjState) {resource ->resource.data?.let { sjList->
            LazyVerticalGrid(
                columns = GridCells.Adaptive(minSize = 300.dp),
                horizontalArrangement = Arrangement.spacedBy(10.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp),
                modifier = Modifier.padding(padding)
            ) {
                items(sjList) { xsItem ->
                    ItemContenMh(itemData = xsItem, navController = navController, marsViewModel)
                }

            }
        }
        }
    }
}
@Composable
fun MhSc(scTjState: Resource<List<DataBean>>, navController: NavController, marsViewModel: MhSjViewModel){
    Column {
        SearchBar(onSearchClick = {
            marsViewModel.getSearchComic(it)
        })
        StateHandler(state = scTjState) {resource ->resource.data?.let { scList->
            ResultScreenMh(
                scList, navController = navController,marsViewModel
            )
        }}
    }
}

//小说书城成功页
@Composable
fun ResultScreenMh(xsListData:List<DataBean>, navController: NavController, marsViewModel: MhSjViewModel) {
    LazyVerticalGrid(
        columns = GridCells.Adaptive(minSize = 300.dp),
        horizontalArrangement = Arrangement.spacedBy(10.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        xsListData?.let {
            items(it) { xsItem ->
                ItemMh(itemData = xsItem, navController = navController,
                    saveComicSelf = {
                        marsViewModel.addComicShelf(xsItem)
                    }
                )
            }
        }
        item {
            Text(text = "无更多数据")
        }
    }
    /*FlowRow (modifier = Modifier.verticalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(20.dp)){
        xsListData.forEach{xsItem->
            ItemXs(itemData = xsItem,navController=navController)
        }
    }*/
}

//漫画推荐展示列表项
@Composable
fun ItemMh(itemData: DataBean, navController: NavController, saveComicSelf: () -> Unit) {
    // 获取 context
    val context = LocalContext.current
    //详情弹窗
    var dialogShow by remember {
        mutableStateOf(false)
    }
    ListItem(onClickItem = {dataBean ->
        Toast.makeText(context, "链接:" + dataBean.url, Toast.LENGTH_LONG)
            .show()
        dialogShow=true
    }, dataBean = itemData)
    if (dialogShow){
        DialogWithImage(onDismissRequest = {dialogShow=false},
            onPlay = { navController.navigate("${PagesMh.MHNR}?url=${itemData.url}&dataId=${itemData.id}") },
            onConfirmation = {
                saveComicSelf()
                Toast.makeText(context, "加入收藏成功", Toast.LENGTH_SHORT).show()
                dialogShow=false},
            itemData
        )
    }
}

//漫画展示列表项
@Composable
fun ItemContenMh(itemData: DataBean, navController: NavController, marsViewModel: MhSjViewModel) {
    // 获取 context
    val context = LocalContext.current
    ListItem(onClickItem = {dataBean ->
        Toast.makeText(context, "链接:" + dataBean.url, Toast.LENGTH_LONG)
            .show()
        navController.navigate("${PagesMh.MHNR}?url=${dataBean.url}&dataId=${dataBean.id}")
    }, dataBean = itemData,
        onDeleteClick = {
            marsViewModel.deleteBookShelf(it)
        }, isDeleteAble = true
    )
}